package com.dubbo.protocol.socket;

import com.dubbo.protocol.Server;
import com.dubbo.protocol.bean.Invocation;
import com.dubbo.protocol.http.HttpHandler;
import com.dubbo.register.RegisterFactory;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

public class SocketServ implements Server
{
    @Override
    public void start(String hostName, int port)
    {
        System.out.println("socket server start...");
        try
        {
            //3代表最多只接受3个客户端连接
            ServerSocket serverSocket = new ServerSocket(port, 3);

            while(true)
            {
                //获取client连接
                Socket socket = serverSocket.accept();

                //线程处理业务
                new Runnable(){
                    @Override
                    public void run() {
                        try
                        {
//                            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//
//                            Invocation invocation = (Invocation) ois.readObject();
//                            System.out.println("httpHandler get invocation: " + invocation);
//
//                            Map<String, Object> localRegister = RegisterFactory.get(RegisterFactory.LOCAL);
//                            Class clazz = (Class) localRegister.get(invocation.getInterfaceName());
//
//                            Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamsClass());
//                            Object result = method.invoke(clazz.newInstance(), invocation.getParamsValue());
//                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//                            oos.writeObject(result);

                            HttpHandler.mainHandler(socket.getInputStream(), socket.getOutputStream());
                        }
                        catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                }.run();
            }
        }
        catch (Exception e)
        {

        }


    }

    public static void main(String[] args)
    {
        System.out.println("socket server start...");
        new SocketServ().start("localhost", 8080);
    }
}
